<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input v-model="searchKeyword" style="margin-bottom:10px" type="text" prefix-icon="el-icon-search" size="small" placeholder="输入员工姓名全员搜索" @input="inputSearch" />
        <!-- 树形组件, 默认全部展开 -->
        <el-tree
          ref="tree"
          node-key="id"
          :data="treeData"
          :props="{label: 'name'}"
          default-expand-all
          highlight-current
          :expand-on-click-node="false"
          @current-change="selectedNodeChange"
        />
      </div>

      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button size="mini" type="primary" @click="$router.push({path:`/employee/detail`})">添加员工</el-button>

          <el-button size="mini" @click="importEmployee">excel导入</el-button>

          <el-button size="mini" :loading="loading.exportEmployee" @click="exportEmployee">excel导出</el-button>

        </el-row>

        <!-- 表格组件 -->
        <el-table :data="tableData" size="small">
          <el-table-column align="center" label="头像" prop="staffPhoto">
            <template #default="obj">
              <el-avatar v-if="obj.row.staffPhoto" size="small" :src="obj.row.staffPhoto" />
              <el-avatar v-else size="small" icon="el-icon-user-solid" />
            </template>
          </el-table-column>
          <el-table-column label="姓名" prop="username" width="120px" />
          <el-table-column label="手机号" sortable prop="mobile" width="120px" />
          <el-table-column label="工号" sortable prop="workNumber" width="120px" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template #default="{row}">
              <span>{{ row.formOfEmployment==1?'正式':'🐃 🐎' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" width="120px" />
          <el-table-column label="入职时间" sortable prop="timeOfEntry" width="120px" />
          <el-table-column label="操作" width="180px">
            <template #default="{row}">
              <el-button size="mini" type="text" @click="$router.push({path:`/employee/detail/${row.id}`})">查看</el-button>
              <el-button size="mini" type="text" style="margin-right:10px;">角色</el-button>
              <el-popconfirm
                title="确定删除吗？"
                @onConfirm="deleteEmployee(row.id)"
              >
                <template #reference>
                  <el-button size="mini" type="text">删除</el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row style="height: 60px" align="middle" type="flex" justify="end">
          <el-pagination
            :page-size="config.pagesize"
            background
            :current-page="config.page"
            layout="total,prev, pager, next"
            :total="config.total"
            @current-change="pageChange"
          />
        </el-row>
      </div>
      <ImportDialog v-model="showDialog.importEmployee" @refresh="getEmployeeList" />
    </div>

  </div>

</template>

<script>
import { getDepartmentList } from '@/api/department'
import { getEmployeeList, exportEmployee, deleteEmployee } from '@/api/employee'
import { convert2Tree } from '@/utils'
import fileSaver from 'file-saver'
import ImportDialog from './components/ImportDialog.vue'
export default {
  name: 'Employee',
  components: {
    ImportDialog
  },
  data() {
    return {
      treeData: [],
      selectedId: -1,
      tableData: [],
      config: {
        page: 1,
        pagesize: 10,
        total: 0
      },
      searchKeyword: '',
      loading: {
        exportEmployee: false
      },
      showDialog: {
        importEmployee: false
      }
      // timer: -1
    }
  },
  created() {
    this.getTreeData()
  },
  methods: {
    /**
     * 获取部门列表
     */
    async getTreeData() {
      const res = await getDepartmentList()
      // 调用函数转换树形结构
      this.treeData = convert2Tree(res)
      this.selectedId = this.treeData[0].id
      this.$nextTick(() => {
        // 默认选中第一个
        // 一定要等到树形组件渲染完成
        this.$refs.tree.setCurrentKey(this.selectedId)
      })
      this.getEmployeeList()
    },
    /**
     * 选中节点变化时
     * @param node 新选择的节点
     */
    selectedNodeChange(node) {
      // console.log(data)
      console.log(node)
      this.selectedId = node.id
      this.config.page = 1
      this.getEmployeeList()
    },
    /**
     * 获取员工列表
     */
    async getEmployeeList() {
      // console.log(this.selectedId)
      const res = await getEmployeeList({
        ...this.config,
        departmentId: this.selectedId,
        keyword: this.searchKeyword
      })
      this.tableData = res.rows
      this.config.total = res.total
      // console.log(res)
    },
    /**
     * @param page 参数表示选择的页码
     * 分页切换时触发
     */
    pageChange(page) {
      this.config.page = page
      this.getEmployeeList()
    },
    inputSearch() {
      clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        this.config.page = 1
        this.getEmployeeList()
      }, 500)
    },
    async deleteEmployee(id) {
      try {
        await deleteEmployee(id)
        this.$message.success('删除成功')
        if (this.tableData.length === 1 && this.config.page > 1) {
          this.config.page--
        }
        this.getEmployeeList()
      } catch (error) {
        this.$message.error('删除失败')
      }
    },
    /**
     * 导出员工
     */
    async exportEmployee() {
      const { exportEmployee: loading } = this.loading
      if (loading) return
      this.loading.exportEmployee = true
      try {
        const a = await exportEmployee()
        console.log(a)
        fileSaver.saveAs(a, '员工列表.xlsx')
      } catch (error) {
        console.log(error)
      } finally {
        // Promise也有.finally(()=>{})方法
        this.loading.exportEmployee = false
      }
    },
    /**
     * 导入员工
     */
    importEmployee() {
      // console.log('导入')
      this.showDialog.importEmployee = true
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .opeate-tools {
      margin:10px ;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04C9BE;
      font-size: 12px;
      display:inline-block;
    }
    .el-table thead tr {
      background-color: #f5f7fa !important;
    }
  }
}

</style>

